package gtdz.ui;

import gtdz.algo.rk4.Record;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;

class EditingCellDouble extends TableCell<Record, Double> {

	private TextField textField;

	public EditingCellDouble() {
	}

	@Override
	public void startEdit() {
		super.startEdit();

		if (textField == null) {
			createTextField();
		}

		setGraphic(textField);
		setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
		textField.selectAll();
	}

	@Override
	public void cancelEdit() {
		super.cancelEdit();

		setText(String.valueOf(getItem()));
		setContentDisplay(ContentDisplay.TEXT_ONLY);
	}

	@Override
	public void updateItem(Double item, boolean empty) {
		super.updateItem(item, empty);

		if (empty) {
			setText(null);
			setGraphic(null);
		} else {
			if (isEditing()) {
				if (textField != null) {
					textField.setText(getString());
				}
				setGraphic(textField);
				setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
			} else {
				setText(getString());
				setContentDisplay(ContentDisplay.TEXT_ONLY);
			}
		}
	}

	private void createTextField() {
		textField = new TextField(getString());
		textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
		textField.setOnKeyPressed(e -> {
				if (e.getCode() == KeyCode.ENTER) {
					commitEdit(Double.parseDouble(textField.getText()));
				} else if (e.getCode() == KeyCode.ESCAPE) {
					cancelEdit();
				}
			});
		textField.focusedProperty().addListener(
			(ObservableValue<? extends Boolean> observalble, Boolean oldVal, Boolean newVal) -> {
				if (!newVal) {
					commitEdit(Double.parseDouble(textField.getText()));
				}
			});
	}

	private String getString() {
		return getItem() == null ? "" : getItem().toString();
	}
}